import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Link} from 'dva/router';
import BusinessUnPayOrderListModal from './BusinessUnPayOrderList';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Table,
  Alert,
} from 'antd';
const {RangePicker} = DatePicker;
import StandardTable from 'components/OrderTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {status, statusMap} from './orderStatus';
import styles from './OrderList.less';
import {stringify} from 'qs';
import {DATA_HOST,} from '../../utils/setting';
import G from '../../utils/g';
import SkuListTable from './BusinessUnPayTable';

const FormItem = Form.Item;
const {Option} = Select;
// const statusMap = ['default', 'processing', 'success', 'error'];
// const status = ['退款成功', '退款退货成功', '退款申请中', '同意退款等待退货', '退款/退货申请中'];
const columns = [
  {
    title: '商家',
    dataIndex: 'goods_nickname',
    key: 'goods_nickname'
  },
  {
    title: '商品',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '型号',
    dataIndex: 'sku',
    key: 'sku',
    render(text, record) {
      let result = '';
      const sku = JSON.parse(record.sku);
      for (let key in sku) {
        result = record.sku[key];
      }
      return result;
    },
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price'
  },
  {
    title: '数量',
    dataIndex: 'total_count',
    key: 'total_count'
  },
  {
    title: '利润',
    dataIndex: 'profit_subtotal',
    key: 'profit_subtotal'
  },
  {
    title: '利润率',
    dataIndex: 'profit_margin',
    key: 'profit_margin'
  },
  {
    title: '销售额',
    dataIndex: 'sale_total',
    key: 'sale_total'
  },
  {
    title: '结算价',
    dataIndex: 'settlement_price',
    key: 'settlement_price'
  },
  {
    title: '结算小计',
    dataIndex: 'settlement_total',
    key: 'settlement_total'
  },
];

const CreateForm = Form.create()(props => {
  const {modalVisible, form, handleAdd, handleModalVisible} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="退款编号">
              {getFieldDecorator('id')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="订单号">
              {getFieldDecorator('orderId')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="退款方式">
              {getFieldDecorator('expected_result')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="退货退款">退货退款</Option>
                  <Option value="仅退款">仅退款</Option>
                </Select>
              )}
            </FormItem>
          </Col>

        </Row>
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="退款状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="200">申请退款</Option>
                  <Option value="201">申请退货</Option>
                  <Option value="202">卖家确认退货</Option>
                  <Option value="203">卖家确认退款</Option>
                  <Option value="204">买家退货</Option>
                  <Option value="205">退款成功</Option>
                  <Option value="206">退款关闭</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="下单时间">
              {getFieldDecorator('time')(
                <RangePicker style={{width: '100%'}} placeholder={['开始日期', '结束日期']}/>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

@connect(({businessPay, loading}) => ({
  businessPay,
  loading: loading.models.businessPay,
}))
@Form.create()
export default class BusinessUnpay extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const {dispatch,
      location
    } = this.props;
    const id = G.getUrlValue('id', location.search);

    dispatch({
      type: 'businessPay/fetchUnPaySku',
      payload: {
        business_id : id
      }
    });
  }

  handleFormReset = () => {
    const {form, dispatch, location} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    const id = G.getUrlValue('id', location.search);
    dispatch({
      type: 'businessPay/fetchUnPaySku',
      payload: {
        business_id: id
      }
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form, location} = this.props;
    const id = G.getUrlValue('id', location.search);

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        business_id: id,
        ...fieldsValue,
      };
      if (Array.isArray(fieldsValue.time)) {
        values.startTime = fieldsValue.time[0].format('YYYY-MM-DD');
        values.endTime = fieldsValue.time[1].format('YYYY-MM-DD');
      }
      delete values.time;

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'businessPay/fetchUnPaySku',
        payload: values
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  renderForm() {
    const {getFieldDecorator} = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="下单时间">
              {getFieldDecorator('time')(
                <RangePicker style={{width: '100%'}} placeholder={['开始日期', '结束日期']}/>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
          <Col md={8} sm={24}>
            <Button type="danger" style={{float: 'right'}} onClick={()=>{this.handleModalVisible(true)}}>
              去结算
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {businessPay: {unPaySkuList = []}, loading, location} = this.props;
    const {selectedRows, modalVisible} = this.state;

    const id = G.getUrlValue('id', location.search);

    const tempSkuList = {};
    unPaySkuList.forEach(v=>{
      const {month_flag} = v;
      if(typeof tempSkuList[month_flag] === 'undefined'){
        tempSkuList[month_flag] = [];
      }
      tempSkuList[month_flag].push(v);
    });

    // console.log(tempSkuList);
    
    const tableList = [];
    for(let key in tempSkuList){
      tableList.push({
        name:key, 
        value:tempSkuList[key]
      })
    }
    
    return (
      <div>
        <Card bordered={false}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        {
          tableList.map(({name, value})=>{
            return <SkuListTable
                      key= {name}
                      data = {value}
                      loading = {loading}
                      month = {name}
                    />
          })
        }
        {/* 
        <SkuListTable
          data = {unPaySkuList}
          loading = {loading}
         /> 
         */}
        <BusinessUnPayOrderListModal
          modalVisible={modalVisible}
          id={id}
          onModalVisible={this.handleModalVisible}
        />
      </div>
    );
  }
}
